package com.tuling.core.listener;

import java.net.URLClassLoader;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;

import com.tuling.core.loader.MyClassLoader;
import com.tuling.core.plugin.PluginCacheUtil;
import com.tuling.core.plugin.PluginInfo;

/**
 * @author Lenovo
 * @描述 ：监听spring加载完成后，初始化配置
 */

public class SpringApplicationListener extends ContextLoaderListener {

	private static Logger LOG = LoggerFactory.getLogger(SpringApplicationListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		super.contextDestroyed(event);
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		super.contextInitialized(event);
		LOG.info("加载一系列初始化……");
		ServletContext servletContext = event.getServletContext();

		ApplicationContext context = (WebApplicationContext) servletContext
				.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

		String path = servletContext.getRealPath("");
		System.out.println(path);
		// 装在默认插件目录下的所有插件
		// 加载我的plugin目录的jar
		MyClassLoader myLoader = MyClassLoader.getClassLoader(path);
		List<PluginInfo> plugins = myLoader.loadPlugins();
		for (PluginInfo plugin : plugins) {
			System.out.println(plugin);
			PluginCacheUtil.addPlugin(plugin.getPluginName(),plugin);
			dynamicAddPlugin(context, plugin.getPluginName(), plugin.getPluginClass(),myLoader);
		}
	}

	/**
	 * @param ac spring context上下文
	 * @param beanId
	 * @param fullClassName
	 */
	private void dynamicAddPlugin(ApplicationContext ac, String beanId, String fullClassName,MyClassLoader myLoader) {
		BeanDefinition bean = new GenericBeanDefinition();
		// 加载类的全路径
		bean.setBeanClassName(fullClassName);
		DefaultListableBeanFactory fty = (DefaultListableBeanFactory) ac.getAutowireCapableBeanFactory();
		// 注册Bean
		// fty.registerBeanDefinition(beanId, bean);
		fty.registerSingleton(beanId, bean);
		setBeanClassLoader(fty,myLoader);
		ac.getBean(beanId); // 如果不get一下，不会触发bean的PostStructure
		
	}

	private void setBeanClassLoader(DefaultListableBeanFactory beanFactory,URLClassLoader loader) {

		beanFactory.setBeanClassLoader(loader);
	}
}
